use std::collections::VecDeque;

use pest::Parser;
use pest::iterators::Pair;

use crate::ast::{
    BinaryOp, Block, Expr, Function, GlobalVar, Item, Parameter, Program, Stmt, Type, UnaryOp,
};
use crate::lexer::{Rule, SysyParser};

/// 解析源代码，返回抽象语法树
pub fn parse_program(source: &str) -> Result<Program, String> {
    let mut pairs = SysyParser::parse(Rule::CompUnit, source).map_err(|e| e.to_string())?;
    let comp_unit = pairs
        .next()
        .ok_or_else(|| "语法分析失败：缺少编译单元".to_string())?;

    let mut items = Vec::new();
    for part in comp_unit.into_inner() {
        match part.as_rule() {
            Rule::Decl => {
                parse_global_decl(part, &mut items)?;
            }
            Rule::VarDecl | Rule::ConstDecl => {
                parse_global_decl(part, &mut items)?;
            }
            Rule::FuncDef => {
                let func = parse_function(part)?;
                items.push(Item::Function(func));
            }
            Rule::TOP_INVALID => {
                return Err(format!("语法错误：无法解析 `{}`", part.as_str()));
            }
            _ => {}
        }
    }
    Ok(Program { items })
}

fn parse_global_decl(pair: Pair<Rule>, out: &mut Vec<Item>) -> Result<(), String> {
    match pair.as_rule() {
        Rule::ConstDecl => {
            let defs = collect_const_defs(pair)?;
            for def in defs {
                out.push(Item::GlobalVar(GlobalVar {
                    is_const: true,
                    name: def.name,
                    init: Some(def.init),
                }));
            }
        }
        Rule::VarDecl => {
            let defs = collect_var_defs(pair)?;
            for def in defs {
                out.push(Item::GlobalVar(GlobalVar {
                    is_const: false,
                    name: def.name,
                    init: def.init,
                }));
            }
        }
        Rule::Decl => {
            for child in pair.into_inner() {
                parse_global_decl(child, out)?;
            }
        }
        _ => {}
    }
    Ok(())
}

fn parse_function(pair: Pair<Rule>) -> Result<Function, String> {
    let mut inner = pair.into_inner();
    let ret_ty = match inner.next() {
        Some(token) if token.as_rule() == Rule::FuncType => match token.as_str() {
            "int" => Type::Int,
            "void" => Type::Void,
            other => return Err(format!("暂不支持的返回类型 `{other}`")),
        },
        _ => return Err("函数缺少返回类型".to_string()),
    };

    let name = inner
        .next()
        .ok_or_else(|| "函数缺少名称".to_string())?
        .as_str()
        .to_string();

    // L_PAREN
    inner.next();

    let mut params = Vec::new();
    let mut next = inner.next().ok_or_else(|| "函数缺少右括号".to_string())?;
    if next.as_rule() == Rule::FuncFParams {
        params = parse_func_params(next)?;
        next = inner.next().ok_or_else(|| "函数缺少右括号".to_string())?;
    }
    debug_assert_eq!(next.as_rule(), Rule::R_PAREN);

    let body_pair = inner.next().ok_or_else(|| "函数缺少函数体".to_string())?;
    let body = parse_block(body_pair)?;

    Ok(Function {
        name,
        ret_type: ret_ty,
        params,
        body,
    })
}

fn parse_func_params(pair: Pair<Rule>) -> Result<Vec<Parameter>, String> {
    let mut params = Vec::new();
    for token in pair.into_inner() {
        match token.as_rule() {
            Rule::FuncFParam => {
                let mut inner = token.into_inner();
                let ty = inner.next().ok_or_else(|| "参数缺少类型".to_string())?;
                if ty.as_str() != "int" {
                    return Err(format!("暂不支持的参数类型 `{}`", ty.as_str()));
                }
                let ident = inner
                    .next()
                    .ok_or_else(|| "参数缺少名称".to_string())?
                    .as_str()
                    .to_string();
                // 不支持数组参数
                for extra in inner {
                    if matches!(
                        extra.as_rule(),
                        Rule::L_BRACKT | Rule::R_BRACKT | Rule::ConstExp
                    ) {
                        return Err("暂不支持数组参数".to_string());
                    }
                }
                params.push(Parameter {
                    name: ident,
                    ty: Type::Int,
                });
            }
            Rule::COMMA => {}
            Rule::PARAM_INVALID => {
                return Err(format!("无效的参数列表片段 `{}`", token.as_str()));
            }
            _ => {}
        }
    }
    Ok(params)
}

fn parse_block(pair: Pair<Rule>) -> Result<Block, String> {
    let mut stmts = Vec::new();
    let mut inner = pair.into_inner().peekable();
    if matches!(inner.peek().map(|p| p.as_rule()), Some(Rule::L_BRACE)) {
        inner.next();
    }
    while let Some(token) = inner.next() {
        match token.as_rule() {
            Rule::BlockItem => {
                let mut inner = token.into_inner();
                if let Some(item) = inner.next() {
                    match item.as_rule() {
                        Rule::Decl => {
                            stmts.extend(parse_local_decl(item)?);
                        }
                        Rule::Stmt => {
                            stmts.push(parse_stmt(item)?);
                        }
                        _ => {}
                    }
                }
            }
            Rule::Stmt => {
                stmts.push(parse_stmt(token)?);
            }
            Rule::Decl => {
                stmts.extend(parse_local_decl(token)?);
            }
            Rule::VarDecl | Rule::ConstDecl => {
                stmts.extend(parse_local_decl(token)?);
            }
            Rule::INVALID => {
                return Err(format!("无效的语句 `{}`", token.as_str()));
            }
            Rule::L_BRACE | Rule::R_BRACE => {}
            _ => {}
        }
    }
    Ok(Block { stmts })
}

fn parse_local_decl(pair: Pair<Rule>) -> Result<Vec<Stmt>, String> {
    match pair.as_rule() {
        Rule::VarDecl => {
            let defs = collect_var_defs(pair)?;
            Ok(defs
                .into_iter()
                .map(|def| Stmt::VarDecl {
                    is_const: false,
                    name: def.name,
                    init: def.init,
                })
                .collect())
        }
        Rule::ConstDecl => {
            let defs = collect_const_defs(pair)?;
            Ok(defs
                .into_iter()
                .map(|def| Stmt::VarDecl {
                    is_const: true,
                    name: def.name,
                    init: Some(def.init),
                })
                .collect())
        }
        Rule::Decl => {
            let mut result = Vec::new();
            for child in pair.into_inner() {
                match child.as_rule() {
                    Rule::VarDecl | Rule::ConstDecl => {
                        result.extend(parse_local_decl(child)?);
                    }
                    Rule::COMMA | Rule::SEMICOLON => {}
                    _ => {}
                }
            }
            Ok(result)
        }
        _ => Ok(Vec::new()),
    }
}

fn parse_stmt(pair: Pair<Rule>) -> Result<Stmt, String> {
    let leading_text = pair.as_str().trim();
    let parts: Vec<_> = pair.into_inner().collect();
    if parts.is_empty() {
        return Err("无法解析的语句".to_string());
    }
    let mut return_seen = parts.iter().any(|p| p.as_rule() == Rule::RETURN);
    let mut first_rule = parts[0].as_rule();
    if !return_seen && first_rule == Rule::Stmt {
        if let Some(stmt_pair) = parts.get(0) {
            let mut inner = stmt_pair.clone().into_inner();
            if let Some(first_inner) = inner.next() {
                first_rule = first_inner.as_rule();
                if first_rule == Rule::RETURN {
                    return_seen = true;
                }
            }
        }
    }
    if !return_seen && leading_text.starts_with("return") {
        return_seen = true;
    }
    if return_seen {
        let rest = leading_text["return".len()..]
            .trim_start()
            .trim_end_matches(';')
            .trim();
        if rest.is_empty() {
            return Ok(Stmt::Return(None));
        }
        let mut parsed = SysyParser::parse(Rule::Exp, rest)
            .map_err(|err| format!("返回表达式解析失败: {}", err))?;
        let exp_pair = parsed
            .next()
            .ok_or_else(|| "返回表达式解析失败".to_string())?;
        let expr = parse_exp_like(exp_pair)?;
        return Ok(Stmt::Return(Some(fold_constant_expr(expr))));
    }
    if parts.iter().any(|p| p.as_rule() == Rule::BREAK) || leading_text.starts_with("break") {
        return Ok(Stmt::Break);
    }
    if parts.iter().any(|p| p.as_rule() == Rule::CONTINUE) || leading_text.starts_with("continue") {
        return Ok(Stmt::Continue);
    }
    match first_rule {
        Rule::LVal => {
            let name = parse_lval(parts[0].clone())?;
            let expr = parse_exp_like(parts[2].clone())?;
            Ok(Stmt::Assign { name, expr })
        }
        Rule::Block => {
            let block = parse_block(parts[0].clone())?;
            Ok(Stmt::Block(block))
        }
        Rule::IF => parse_if_stmt(&parts),
        Rule::WHILE => parse_while_stmt(&parts),
        Rule::SEMICOLON => Ok(Stmt::Expr(Expr::Int(0))),
        Rule::Exp => {
            let expr = parse_exp_like(parts[0].clone())?;
            Ok(Stmt::Expr(expr))
        }
        Rule::BlockItem => unreachable!(),
        _ => Err(format!("暂不支持的语句 `{}`", parts[0].as_str())),
    }
}

fn parse_if_stmt(parts: &[Pair<Rule>]) -> Result<Stmt, String> {
    // IF ( Cond ) Stmt (ELSE Stmt)?
    let cond = parts
        .iter()
        .find(|p| p.as_rule() == Rule::Cond)
        .ok_or_else(|| "if 语句缺少条件".to_string())?
        .clone();
    let cond_expr = parse_cond(cond)?;

    let then_part = parts
        .iter()
        .find(|p| p.as_rule() == Rule::Stmt)
        .ok_or_else(|| "if 语句缺少 then 分支".to_string())?
        .clone();
    let then_stmt = parse_stmt(then_part)?;

    let else_stmt = if parts.iter().any(|p| p.as_rule() == Rule::ELSE) {
        let else_part = parts
            .iter()
            .rev()
            .find(|p| p.as_rule() == Rule::Stmt)
            .ok_or_else(|| "if-else 语句缺少 else 分支".to_string())?
            .clone();
        let parsed = parse_stmt(else_part)?;
        Some(Box::new(parsed))
    } else {
        None
    };

    Ok(Stmt::If {
        cond: cond_expr,
        then_branch: Box::new(then_stmt),
        else_branch: else_stmt,
    })
}

fn parse_while_stmt(parts: &[Pair<Rule>]) -> Result<Stmt, String> {
    let cond = parts
        .iter()
        .find(|p| p.as_rule() == Rule::Cond)
        .ok_or_else(|| "while 语句缺少条件".to_string())?
        .clone();
    let cond_expr = parse_cond(cond)?;

    let body_part = parts
        .iter()
        .find(|p| p.as_rule() == Rule::Stmt)
        .ok_or_else(|| "while 语句缺少循环体".to_string())?
        .clone();
    let body = parse_stmt(body_part)?;

    Ok(Stmt::While {
        cond: cond_expr,
        body: Box::new(body),
    })
}

fn parse_cond(pair: Pair<Rule>) -> Result<Expr, String> {
    let lor = pair
        .into_inner()
        .next()
        .ok_or_else(|| "条件缺少表达式".to_string())?;
    parse_lor_exp(lor)
}

fn parse_exp_like(pair: Pair<Rule>) -> Result<Expr, String> {
    match pair.as_rule() {
        Rule::Exp => {
            let inner = pair.into_inner().next().unwrap();
            parse_add_exp(inner)
        }
        _ => parse_add_exp(pair),
    }
}

fn parse_lor_exp(pair: Pair<Rule>) -> Result<Expr, String> {
    let mut inner = pair.into_inner();
    let first = inner.next().ok_or_else(|| "缺少表达式".to_string())?;
    let mut expr = parse_land_exp(first)?;
    let mut queue: VecDeque<_> = inner.collect();
    while let Some(op) = queue.pop_front() {
        if op.as_rule() == Rule::OR {
            let rhs_pair = queue
                .pop_front()
                .ok_or_else(|| "逻辑或表达式缺少右端".to_string())?;
            let rhs = parse_land_exp(rhs_pair)?;
            expr = Expr::Binary {
                op: BinaryOp::Or,
                lhs: Box::new(expr),
                rhs: Box::new(rhs),
            };
        }
    }
    Ok(expr)
}

fn parse_land_exp(pair: Pair<Rule>) -> Result<Expr, String> {
    let mut inner = pair.into_inner();
    let first = inner.next().ok_or_else(|| "缺少表达式".to_string())?;
    let mut expr = parse_eq_exp(first)?;
    let mut queue: VecDeque<_> = inner.collect();
    while let Some(op) = queue.pop_front() {
        if op.as_rule() == Rule::AND {
            let rhs_pair = queue
                .pop_front()
                .ok_or_else(|| "逻辑与表达式缺少右端".to_string())?;
            let rhs = parse_eq_exp(rhs_pair)?;
            expr = Expr::Binary {
                op: BinaryOp::And,
                lhs: Box::new(expr),
                rhs: Box::new(rhs),
            };
        }
    }
    Ok(expr)
}

fn parse_eq_exp(pair: Pair<Rule>) -> Result<Expr, String> {
    fold_binary(
        pair,
        parse_rel_exp,
        &[Rule::EQ, Rule::NEQ],
        |rule| match rule {
            Rule::EQ => BinaryOp::Eq,
            Rule::NEQ => BinaryOp::Ne,
            _ => unreachable!(),
        },
    )
}

fn parse_rel_exp(pair: Pair<Rule>) -> Result<Expr, String> {
    fold_binary(
        pair,
        parse_add_exp,
        &[Rule::LT, Rule::GT, Rule::LE, Rule::GE],
        |rule| match rule {
            Rule::LT => BinaryOp::Lt,
            Rule::GT => BinaryOp::Gt,
            Rule::LE => BinaryOp::Le,
            Rule::GE => BinaryOp::Ge,
            _ => unreachable!(),
        },
    )
}

fn parse_add_exp(pair: Pair<Rule>) -> Result<Expr, String> {
    fold_binary(
        pair,
        parse_mul_exp,
        &[Rule::PLUS, Rule::MINUS],
        |rule| match rule {
            Rule::PLUS => BinaryOp::Add,
            Rule::MINUS => BinaryOp::Sub,
            _ => unreachable!(),
        },
    )
}

fn parse_mul_exp(pair: Pair<Rule>) -> Result<Expr, String> {
    fold_binary(
        pair,
        parse_unary_exp,
        &[Rule::MUL, Rule::DIV, Rule::MOD],
        |rule| match rule {
            Rule::MUL => BinaryOp::Mul,
            Rule::DIV => BinaryOp::Div,
            Rule::MOD => BinaryOp::Mod,
            _ => unreachable!(),
        },
    )
}

fn fold_binary<F, G>(
    pair: Pair<Rule>,
    mut parse_operand: F,
    ops: &[Rule],
    map_op: G,
) -> Result<Expr, String>
where
    F: FnMut(Pair<Rule>) -> Result<Expr, String>,
    G: Fn(Rule) -> BinaryOp,
{
    let mut inner = pair.into_inner();
    let first = inner.next().ok_or_else(|| "缺少表达式".to_string())?;
    let mut expr = parse_operand(first)?;

    let mut queue: VecDeque<_> = inner.collect();
    while let Some(op_token) = queue.pop_front() {
        if ops.contains(&op_token.as_rule()) {
            let rhs_pair = queue
                .pop_front()
                .ok_or_else(|| "二元表达式缺少右端".to_string())?;
            let rhs = parse_operand(rhs_pair)?;
            expr = Expr::Binary {
                op: map_op(op_token.as_rule()),
                lhs: Box::new(expr),
                rhs: Box::new(rhs),
            };
        }
    }
    Ok(expr)
}

fn parse_unary_exp(pair: Pair<Rule>) -> Result<Expr, String> {
    let mut inner = pair.into_inner();
    if let Some(first) = inner.next() {
        match first.as_rule() {
            Rule::UnaryOp => {
                let op = match first.into_inner().next() {
                    Some(tok) => match tok.as_rule() {
                        Rule::PLUS => UnaryOp::Pos,
                        Rule::MINUS => UnaryOp::Neg,
                        Rule::NOT => UnaryOp::Not,
                        _ => return Err("未知的一元运算符".to_string()),
                    },
                    None => return Err("缺少一元运算符".to_string()),
                };
                let expr_pair = inner
                    .next()
                    .ok_or_else(|| "一元运算缺少右操作数".to_string())?;
                let expr = parse_unary_exp(expr_pair)?;
                Ok(Expr::Unary {
                    op,
                    expr: Box::new(expr),
                })
            }
            Rule::PrimaryExp => parse_primary_exp(first),
            Rule::IDENT => {
                let name = first.as_str().to_string();
                let mut args = Vec::new();
                // 跳过 L_PAREN
                inner.next();
                if let Some(next) = inner.next() {
                    match next.as_rule() {
                        Rule::FuncRParams => {
                            args = parse_call_args(next)?;
                            // 跳过 R_PAREN
                            inner.next();
                        }
                        Rule::R_PAREN => {}
                        _ => {}
                    }
                }
                Ok(Expr::Call { name, args })
            }
            _ => Err(format!("无法解析的一元表达式 `{}`", first.as_str())),
        }
    } else {
        Err("空的一元表达式".to_string())
    }
}

fn parse_primary_exp(pair: Pair<Rule>) -> Result<Expr, String> {
    let mut inner = pair.into_inner();
    let first = inner.next().ok_or_else(|| "空的基础表达式".to_string())?;
    match first.as_rule() {
        Rule::L_PAREN => {
            let exp_pair = inner
                .next()
                .ok_or_else(|| "缺少括号内的表达式".to_string())?;
            let expr = parse_exp_like(exp_pair)?;
            Ok(expr)
        }
        Rule::Exp => parse_exp_like(first),
        Rule::LVal => {
            let name = parse_lval(first)?;
            Ok(Expr::Variable(name))
        }
        Rule::Number => parse_number(first),
        _ => Err(format!("无法解析的基础表达式 `{}`", first.as_str())),
    }
}

fn parse_call_args(pair: Pair<Rule>) -> Result<Vec<Expr>, String> {
    let mut args = Vec::new();
    for token in pair.into_inner() {
        match token.as_rule() {
            Rule::Exp => {
                args.push(parse_exp_like(token)?);
            }
            Rule::COMMA => {}
            Rule::ARGS_INVALID => {
                return Err(format!("无效的实参 `{}`", token.as_str()));
            }
            _ => {}
        }
    }
    Ok(args)
}

fn parse_lval(pair: Pair<Rule>) -> Result<String, String> {
    let mut inner = pair.into_inner();
    let ident = inner
        .next()
        .ok_or_else(|| "缺少标识符".to_string())?
        .as_str()
        .to_string();
    if inner.next().is_some() {
        return Err("暂不支持数组下标访问".to_string());
    }
    Ok(ident)
}

fn parse_number(pair: Pair<Rule>) -> Result<Expr, String> {
    let mut inner = pair.into_inner();
    let num = inner.next().ok_or_else(|| "缺少数字".to_string())?.as_str();
    let value = parse_int_literal(num)?;
    Ok(Expr::Int(value))
}

fn parse_int_literal(text: &str) -> Result<i32, String> {
    let value = if let Some(rest) = text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
        i32::from_str_radix(rest, 16)
    } else if text.starts_with('0') && text.len() > 1 {
        i32::from_str_radix(&text[1..], 8)
    } else {
        i32::from_str_radix(text, 10)
    };
    value.map_err(|_| format!("整数常量 `{text}` 超出范围"))
}

#[derive(Debug)]
struct VarInit {
    name: String,
    init: Expr,
}

#[derive(Debug)]
struct MaybeInit {
    name: String,
    init: Option<Expr>,
}

fn collect_const_defs(pair: Pair<Rule>) -> Result<Vec<VarInit>, String> {
    let mut defs = Vec::new();
    for token in pair.into_inner() {
        match token.as_rule() {
            Rule::ConstDef => {
                let mut inner = token.into_inner();
                let name = inner
                    .next()
                    .ok_or_else(|| "常量缺少名称".to_string())?
                    .as_str()
                    .to_string();
                for extra in inner.by_ref() {
                    match extra.as_rule() {
                        Rule::ConstInitVal => {
                            let expr = fold_constant_expr(parse_const_init(extra)?);
                            defs.push(VarInit { name, init: expr });
                            break;
                        }
                        Rule::L_BRACKT | Rule::R_BRACKT | Rule::ConstExp => {
                            return Err("暂不支持常量数组".to_string());
                        }
                        _ => {}
                    }
                }
            }
            Rule::COMMA => {}
            Rule::CONSTDEF_INVALID => {
                return Err(format!("无效的常量定义 `{}`", token.as_str()));
            }
            Rule::SEMICOLON => {}
            _ => {}
        }
    }
    Ok(defs)
}

fn collect_var_defs(pair: Pair<Rule>) -> Result<Vec<MaybeInit>, String> {
    fn parse_var_def(token: Pair<Rule>) -> Result<MaybeInit, String> {
        let mut inner = token.into_inner();
        let name = inner
            .next()
            .ok_or_else(|| "变量缺少名称".to_string())?
            .as_str()
            .to_string();
        let mut init = None;
        let mut pending_assign = false;
        for extra in inner {
            match extra.as_rule() {
                Rule::L_BRACKT | Rule::R_BRACKT | Rule::ConstExp => {
                    return Err("暂不支持数组变量".to_string());
                }
                Rule::ASSIGN => pending_assign = true,
                Rule::InitVal => {
                    if pending_assign {
                        let expr = parse_init_val(extra)?;
                        init = Some(fold_constant_expr(expr));
                        pending_assign = false;
                    }
                }
                Rule::Exp => {
                    if pending_assign {
                        let expr = parse_exp_like(extra)?;
                        init = Some(fold_constant_expr(expr));
                        pending_assign = false;
                    }
                }
                _ => {}
            }
        }
        Ok(MaybeInit { name, init })
    }

    let mut defs = Vec::new();
    let mut inner = pair.into_inner().peekable();
    if matches!(inner.peek().map(|p| p.as_rule()), Some(Rule::BType)) {
        inner.next();
    }
    while let Some(token) = inner.next() {
        match token.as_rule() {
            Rule::VarDef => defs.push(parse_var_def(token)?),
            Rule::COMMA | Rule::SEMICOLON => {}
            Rule::VARDEF_INVALID => {
                return Err(format!("无效的变量定义 `{}`", token.as_str()));
            }
            _ => {}
        }
    }
    Ok(defs)
}

fn fold_constant_expr(expr: Expr) -> Expr {
    match expr {
        Expr::Int(_) | Expr::Variable(_) | Expr::Call { .. } => expr,
        Expr::Unary { op, expr } => {
            let inner = fold_constant_expr(*expr);
            match (op, inner) {
                (UnaryOp::Pos, Expr::Int(v)) => Expr::Int(v),
                (UnaryOp::Neg, Expr::Int(v)) => Expr::Int(-v),
                (UnaryOp::Not, Expr::Int(v)) => Expr::Int((v == 0) as i32),
                (op, inner) => Expr::Unary {
                    op,
                    expr: Box::new(inner),
                },
            }
        }
        Expr::Binary { op, lhs, rhs } => {
            let left = fold_constant_expr(*lhs);
            let right = fold_constant_expr(*rhs);
            match (&left, &right) {
                (Expr::Int(l), Expr::Int(r)) => {
                    let value = match op {
                        BinaryOp::Add => Some(l.wrapping_add(*r)),
                        BinaryOp::Sub => Some(l.wrapping_sub(*r)),
                        BinaryOp::Mul => Some(l.wrapping_mul(*r)),
                        BinaryOp::Div => {
                            if *r != 0 {
                                Some(l / r)
                            } else {
                                None
                            }
                        }
                        BinaryOp::Mod => {
                            if *r != 0 {
                                Some(l % r)
                            } else {
                                None
                            }
                        }
                        BinaryOp::Lt => Some((*l < *r) as i32),
                        BinaryOp::Le => Some((*l <= *r) as i32),
                        BinaryOp::Gt => Some((*l > *r) as i32),
                        BinaryOp::Ge => Some((*l >= *r) as i32),
                        BinaryOp::Eq => Some((*l == *r) as i32),
                        BinaryOp::Ne => Some((*l != *r) as i32),
                        BinaryOp::And => Some(((*l != 0) && (*r != 0)) as i32),
                        BinaryOp::Or => Some(((*l != 0) || (*r != 0)) as i32),
                    };
                    if let Some(v) = value {
                        Expr::Int(v)
                    } else {
                        Expr::Binary {
                            op,
                            lhs: Box::new(left),
                            rhs: Box::new(right),
                        }
                    }
                }
                _ => Expr::Binary {
                    op,
                    lhs: Box::new(left),
                    rhs: Box::new(right),
                },
            }
        }
    }
}

fn parse_const_init(pair: Pair<Rule>) -> Result<Expr, String> {
    let inner: Vec<_> = pair.into_inner().collect();
    if inner.is_empty() {
        return Err("常量初始化缺少表达式".to_string());
    }
    if inner[0].as_rule() == Rule::ConstExp {
        let exp = inner[0].clone();
        let add_exp = exp.into_inner().next().unwrap();
        parse_add_exp(add_exp)
    } else {
        Err("暂不支持数组常量初始化".to_string())
    }
}

fn parse_init_val(pair: Pair<Rule>) -> Result<Expr, String> {
    let inner: Vec<_> = pair.into_inner().collect();
    if inner.is_empty() {
        return Err("变量初始化缺少表达式".to_string());
    }
    if inner[0].as_rule() == Rule::Exp {
        parse_exp_like(inner[0].clone())
    } else {
        Err("暂不支持聚合初始化".to_string())
    }
}
